package com.example.e_book.Activity;

import android.os.Bundle;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.e_book.BorderScrollView;
import com.example.e_book.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadActivity extends AppCompatActivity {

    private TextView contentTextView;
    private String allContent; // 存储文件所有内容
    private int currentOffset = 0; // 当前读取的偏移量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read);

        contentTextView = findViewById(R.id.contentTextView);

        // 获取传递的书籍内容路径
        String contentPath = getIntent().getStringExtra("CONTENT_PATH");
        if (contentPath != null) {
            // 从assets目录读取书籍内容
            allContent = readTextFromAssets(contentPath);
            loadMoreContent();
        }

        BorderScrollView scrollView = findViewById(R.id.scrollView);
        scrollView.setOnScrollListener(new BorderScrollView.OnScrollListener() {
            @Override
            public void onScrollChanged(ScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (y == scrollView.getChildAt(0).getHeight() - scrollView.getHeight()) {
                    loadMoreContent();
                }
            }
        });
    }

    private void loadMoreContent() {
        if (allContent != null && currentOffset < allContent.length()) {
            int pageSize = 10000; // 每次加载10000个字符
            String pageContent = allContent.substring(currentOffset, Math.min(currentOffset + pageSize, allContent.length()));
            contentTextView.append(pageContent);
            currentOffset += pageSize;
        }
    }

    public String readTextFromAssets(String fileName) {
        StringBuilder content = new StringBuilder();
        try {
            InputStream inputStream = getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}